package com.gomore.opple.module.main.home;

import android.app.AlertDialog;
import android.graphics.Paint;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gomore.opple.R;
import com.gomore.opple.model.EventQueryShoppingCar;
import com.gomore.opple.model.ReflahEvent;
import com.gomore.opple.module.BaseFragmentV4;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.main.home.adapter.ConsumerAdapter;
import com.gomore.opple.service.ConsumerClickListener;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.widgets.PullBaseView;
import com.gomore.opple.widgets.PullRecyclerView;
import com.gomore.opple.widgets.adapter.MultiItemTypeAdapter;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by asus on 2017/5/9.
 */
public class HomeFragment extends BaseFragmentV4 implements HomeContract.View,
        PullBaseView.OnRefreshListener, ConsumerClickListener {

    private HomeContract.Presenter mPresenter;
    private ConsumerAdapter consumerAdapter;
    @Bind(R.id.recyclerView)
    PullRecyclerView recyclerView;
    @Bind(R.id.empty_view)
    View empty_view;
    @Bind(R.id.customer_add)
    ImageView customer_add;
    @Bind(R.id.search_text)
    EditText search_text;
    @Bind(R.id.search)
    TextView search;
    private String nameAndMobile;
    private boolean showDialog;

    public static HomeFragment getInstance() {
        return new HomeFragment();
    }

    @Override
    protected void initalizeData() {
        super.initalizeData();
        EventBus.getDefault().register(this);
        showDialog = true;
        mPresenter.getConsumer(nameAndMobile, false, showDialog);
    }

    @Override
    protected void initalizeViews() {
        super.initalizeViews();
        consumerAdapter = new ConsumerAdapter(getActivity(), R.layout.consumer_item, mPresenter.getData());
        recyclerView.setLayoutManager(new LinearLayoutManager(HomeFragment.this.getActivity()));
        recyclerView.setAdapter(consumerAdapter);
        recyclerView.setOnRefreshListener(this);
        consumerAdapter.setConsumerClickListener(this);
        consumerAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                IntentStart.getInstance().startAddConsumerActivity(getActivity(), mPresenter.getData().get(position).getConsumer());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        search_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                nameAndMobile = str;
            }
        });
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_home;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    /**
     * 加载完毕
     */
    @Override
    public void showLoadMoreCompleted() {
        recyclerView.onFooterRefreshComplete();
    }

    /**
     * 刷新完毕
     */
    @Override
    public void showRefreshCompleted() {
        recyclerView.onHeaderRefreshComplete();
    }

    @Override
    public void showContent() {
        consumerAdapter.notifyDataSetChanged();
        if (mPresenter.getData().size() == 0) {
            empty_view.setVisibility(View.VISIBLE);
        } else {
            empty_view.setVisibility(View.GONE);
        }
    }

    @Override
    public void reflashView() {
        showDialog = false;
        mPresenter.getConsumer(nameAndMobile, false, showDialog);
    }

    @Override
    public void showDialog() {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.save_store_code_dialog, null);

        final EditText store_code_edt = (EditText) layout.findViewById(R.id.store_code_edt);
        final TextView detail = (TextView) layout.findViewById(R.id.detail);
        final RelativeLayout buttom_bg = (RelativeLayout) layout.findViewById(R.id.buttom_bg);
        TextView dialog_confirm = (TextView) layout.findViewById(R.id.confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        int screenWidth = DensityUtil.screenWith(getActivity());
        //buttom_bg宽高设置
        int width = screenWidth * 9 / 10;
        int heigeht = width * 261 / 926;
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, heigeht);
        buttom_bg.setLayoutParams(layoutParams);

        android.view.WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = width * 914 / 926;   //高度设置为屏幕的0.9*914/926
        p.width = width;    //宽度设置为屏幕的0.9
        alertDialog.getWindow().setAttributes(p);     //设置生效

        detail.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        dialog_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(store_code_edt.getText().toString().trim())) {
                    showMessage("请输入门店代码");
                    return;
                }
                mPresenter.saveStoreCode(store_code_edt.getText().toString().trim());
                alertDialog.dismiss();
            }
        });

        detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentStart.getInstance().startViewPictureActivity(getActivity());
            }
        });
    }

    @Override
    public void goToAddressDialog(String storeCode) {
        IntentStart.getInstance().startAddressDialogActivity(getActivity(), storeCode);
    }

    @Override
    public void setPresenter(HomeContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onHeaderRefresh(PullBaseView view) {
        showDialog = false;
        mPresenter.getConsumer(nameAndMobile, false, showDialog);
    }

    @Override
    public void onFooterRefresh(PullBaseView view) {
        showDialog = false;
        mPresenter.getConsumer(nameAndMobile, true, showDialog);
    }

    @OnClick({R.id.customer_add, R.id.search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.customer_add:
                IntentStart.getInstance().startAddConsumerActivity(getActivity(), null);
                break;
            case R.id.search:
                if (TextUtils.isEmpty(nameAndMobile)) {
                    nameAndMobile = null;
                }
                showDialog = false;
                mPresenter.getConsumer(nameAndMobile, false, showDialog);
                break;
        }
    }

    @Override
    public void select(String consumerId, boolean updateTime) {
        if (updateTime) {
            if (consumerId != null) {
                //添加客户后者是修改客户回到主页
                mPresenter.saveTime(consumerId);
                EventQueryShoppingCar eventQueryShoppingCar = new EventQueryShoppingCar();
                eventQueryShoppingCar.setIsGetShoppingCar(true);
                EventBus.getDefault().post(eventQueryShoppingCar);
            }
        } else {
            reflashView();
        }
    }

    public void onEventMainThread(ReflahEvent reflahEvent) {
        if (reflahEvent.isReflash() && reflahEvent.getConsumerId() != null) {
            mPresenter.saveTime(reflahEvent.getConsumerId());
            EventQueryShoppingCar eventQueryShoppingCar = new EventQueryShoppingCar();
            eventQueryShoppingCar.setIsGetShoppingCar(true);
            EventBus.getDefault().post(eventQueryShoppingCar);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
